package com.eleMall.timedTask;

import com.eleMall.entity.Market;
import com.eleMall.service.MarketService;
import com.eleMall.util.getMarkets;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author XiMen
 * @version 1.0
 * @description 定时从新发地接收数据更新数据库
 * @date 2024/3/21 21:37
 */
@Slf4j
@Component
public class marketsJob implements Job {
    public marketsJob(){}
    @Autowired
    private MarketService marketService;
    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<Market> markets = getMarkets.getMarkets();
        Date current_time = new Date();
        String strDate = dateToStr(current_time, "yyyy-MM-dd HH:mm:ss");
        java.sql.Timestamp op_time = strToSqlDate(strDate, "yyyy-MM-dd HH:mm:ss");
        marketService.remove(null);
        System.out.println("删除后表中数据还有"+marketService.count());
        marketService.saveBatch(markets);
        log.info("-----今日数据已更新----");
    }
    public static String dateToStr(java.util.Date date, String strFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(strFormat);
        String str = sf.format(date);
        return str;
    }

    public static java.sql.Timestamp strToSqlDate(String strDate, String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        java.util.Date date = null;
        try {
            date = sf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Timestamp dateSQL = new java.sql.Timestamp(date.getTime());
        return dateSQL;
    }
}
